package com.ymy.thinking.in.spring.dependency.injection;

import com.ymy.thinking.in.spring.dependency.injection.annotation.MyAutowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.inject.Inject;
import java.util.Optional;

/**
 * {@link javax.inject.Inject} 注解使用示例
 * <p>
 * {@link AutowiredAnnotationBeanPostProcessor} 既可以处理 {@link Autowired} 也可以处理 {@link Inject} 注解
 *
 * @author Ringo
 * @date 2021/10/18 21:31
 */
public class InjectAnnotationDemo {

    @Inject
    public User user;

    /**
     * 测试自定义注解 DI
     */
    @MyAutowired
    public Optional<User> user1;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(InjectAnnotationDemo.class);
        InjectAnnotationDemo instance = applicationContext.getBean(InjectAnnotationDemo.class);
        System.out.println(instance.user);
        System.out.println(instance.user1.orElseThrow(() -> new RuntimeException("自定义注解依赖注入失败")));
    }


    @Bean
    public User user() {
        return new User("zs", 17);
    }

}
